/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package businesscard.DAO;

import bc.entity.Binhluan;
import bc.entity.User;
import bc.util.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Welcome
 */
public class BinhluanDAO {
    private Session session;
    public BinhluanDAO(){
        SessionFactory factory= HibernateUtil.getSessionFactory();
        // this.session = factory.getCurrentSession();
        this.session=factory.openSession();
    }
    public void Save(Binhluan A){
        try{
            session.getTransaction().begin();
            session.save(A);
            session.flush();
            session.getTransaction().commit();
        }catch(Exception e){
            if(session.getTransaction().isActive())
                session.getTransaction().rollback();
            e.printStackTrace();
        }
    }
    public Binhluan[] getAllBinhluan(int id_lienhe){
        try {
            session.getTransaction().begin();
            String sql = "from Binhluan where id_lienhe= ?";
            Query query = session.createQuery(sql);
             query.setInteger(0,id_lienhe);
            List result=query.list();
           Binhluan[] binhluanList = new Binhluan[result.size()];
            result.toArray(binhluanList);
            session.flush();
            session.getTransaction().commit();
            return binhluanList;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }
    public String getLinkHinh(int id_user){
        try{
//            session.getTransaction().begin();
            String sql="from User where id_user = ?";
            Query query=session.createQuery(sql);
            query.setInteger(0, id_user);       
            User result=(User)query.uniqueResult();
            String hinh=result.getHinhanh();   
//            session.flush();
//            session.getTransaction().commit();
            return hinh;
        }catch(Exception e){
//            if(session.getTransaction().isActive())
//                session.getTransaction().rollback();
            e.printStackTrace();
        }
        return "";
    }
    public static void main(String[] args) {
        BinhluanDAO A=new BinhluanDAO();
        Binhluan[] B=A.getAllBinhluan(1);
        for(int i=0;i<B.length;i++){
           // System.out.println(B[i].getBinhluan());
            int id=B[i].getUser().getIdUser();
            System.out.println(A.getLinkHinh(id));
            
        }
        
    }
}
